import { observer, useLocalObservable } from 'mobx-react'
import styles from './index.module.less'
import Store from './store'
import BtnBotLayout from '@/components/BtnBotLayout'
import EasyModal from '@/components/EasyModal'
import PageLoading from '@/components/Global/PageLoading'
import { getQuestionByType } from '../../archives/components'
import { history, useLocation } from 'umi'
import { useEffect, useState } from 'react'
import { getData } from '@/servers/http'
import { api } from '@/servers/api'
import { Toast } from 'antd-mobile'
import { setUserCenterCookies } from '@/utils/userCenter'
import dayjs from 'dayjs'
import { getLocalStorage } from '@/storage'

export default observer(() => {
    const identityType = getLocalStorage('IDENTITY_TYPE')
    const store = useLocalObservable(() => new Store())
    const { barriersInfo, visible, handleClose, id } = store
    const { messageCode, success, message } = useLocation().query
    const [isEnd, setIsEnd] = useState(false)

    useEffect(() => {
        getData(api.usersLoginUserInfo).then((res: any) => {
            const { data, status } = res
            if (status !== 200) return
            setIsEnd(dayjs().isAfter(dayjs(data?.userStudent?.end_class_time).endOf('day')))
        })
        switch (messageCode) {
            case 'BUSINESS_QUESTIONNAIRE_NO_PUBLISH_ERROR':
                Toast.show('问卷已停止收集')
                break
            case 'BUSINESS_QUESTIONNAIRE_TIME_UPDATE':
                Toast.show('问卷内容已更新')
                break
            default:
                if (success === 'false') {
                    Toast.show(message || '提交失败')
                }
                break
        }
    }, [])

    if (!barriersInfo) {
        return <PageLoading />
    }

    const { detail, scene_id, nextScene, name } = barriersInfo
    const { items, originalData } = detail || {}
    document.title = name

    /** 下一关 */
    const onFinish = () => {
        history.push(`/level?id=${nextScene?.id || scene_id}`)
    }

    /** 编辑 */
    const onEdit = () => {
        getData(api.usersLoginUserInfo).then((res: any) => {
            const { data, status } = res
            if (status !== 200) return
            const callbackUrl = encodeURIComponent(window.location.origin + `/#/questionnaire/result/${id}?rCode=${detail.code}`)
            const { platform_access_token, mid_domain, platform_site_id, imitate_site_id, platform_site_alias, imitate_site_alias, platform_usercode } = data || {}
            setUserCenterCookies(
                {
                    h5Token: platform_access_token,
                    h5SelectUserType: '1',
                    h5UserCode: platform_usercode,
                    h5Alias: Number(identityType) === 2 ? imitate_site_alias : platform_site_alias,
                },
                Number(identityType) === 2 ? imitate_site_id : platform_site_id,
            )
            window.location.href = `${mid_domain}/question-center/collecting?code=${barriersInfo?.code}&collectCode=${barriersInfo.detail.code}&h5Back=${callbackUrl}&fill=edit`
            // window.location.href = `https://sh-questionnaire.cloud.wozp.cn/collecting?code=${barriersInfo?.code}&token=${platform_access_token}&h5Back=${callbackUrl}&fill=edit`
        })
    }

    return (
        <div className={styles.container}>
            <BtnBotLayout
                footer={
                    <div className={styles.options_wrapper}>
                        {!isEnd && (
                            <div className={styles.white} onClick={onEdit}>
                                重新编辑
                            </div>
                        )}
                        <div className={styles.blue} onClick={onFinish}>
                            下一关
                        </div>
                    </div>
                }
            >
                <div className={styles.ques_list}>
                    {items
                        ?.filter((item: any) => item.type !== 7)
                        ?.map((item, idx) => {
                            const { type, code, scheme } = item
                            const Comp = getQuestionByType(type)
                            if (!Comp) {
                                return null
                            }
                            return <Comp key={code} scheme={scheme} answers={originalData[code]} idx={idx + 1} />
                        })}
                </div>

                <EasyModal visible={visible} onClose={handleClose} title="任务完成" content={`关卡${barriersInfo.sort}：${barriersInfo.name}，档案已完成`} onOk={handleClose} />
            </BtnBotLayout>
        </div>
    )
})
